package com.xlhj.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: lcj
 * @Date: 2020/11/18 15:35
 * @Description: TODO
 * @Version: 0.0.1
 */
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    public static Map<String, ChannelHandlerContext> contextMap = new ConcurrentHashMap<String, ChannelHandlerContext>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String msgStr = new String(bytes, "UTF-8");
        System.out.println("Read from Client:" + msgStr);
        String resStr = "hello client";
        ByteBuf resp = Unpooled.copiedBuffer(resStr.getBytes());
        ctx.write(resp);
        System.out.println(resp);
        //ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
